﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Web.Services;
using OurSite.Business.Category;
using OurSite.Business.Event;
using OurSite.Business.Helper;
using OurSite.Business.Picture;
using OurSite.Business.Repositories;
using OurSite.Business.Video;

namespace OurSite.WebAdmin
{
    /// <summary>
    /// Summary description for iPhoto
    /// </summary>
    [WebService(Namespace = "http://www.activeexposure.com/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
    // [System.Web.Script.Services.ScriptService]
    public class iPhoto : System.Web.Services.WebService
    {
        protected string SuccessMessage = "OK";

        [WebMethod]
        public List<int> GetAllYears()
        {
            IEventRepository repository = new EventRepository();
            var evts = repository.GetDistinctAllYears().ToList();
            return evts;
        }

        [WebMethod]
        public List<EventLight> GetEventsByYear(int year)
        {
            IEventRepository repository = new EventRepository();
            var evts = repository.GetEventLightsByYear(year);
            return evts;
        }

        [WebMethod]
        public List<EventLight> GetAllEvents()
        {
            IEventRepository repository = new EventRepository();
            var evts = repository.GetAllEventLights();
            return evts;
        }

        [WebMethod]
        public EventLight GetEventByID(Guid id)
        {
            IEventRepository repository = new EventRepository();
            var evts = repository.GetEventLightById(id);
            return evts;
        }

        [WebMethod]
        public string CreateEvent(EventLight evtl)
        {
            try
            {
                IEventRepository repository = new EventRepository();
                var evt = new Event
                    {
                        EventCode = repository.GetNextEventCode(),
                        ParentId = evtl.ParentId,
                        Name = evtl.Name,
                        StartDate = Convert.ToDateTime(evtl.StartDate),
                        EndDate = Convert.ToDateTime(evtl.EndDate),
                        ShortDescription = evtl.ShortDescription,
                        LongDescription = evtl.LongDescription,
                        Region = evtl.Region,
                        Country = evtl.Country,
                        State = evtl.State,
                        City = evtl.City,
                        Location = evtl.Location,
                        Order = 1,
                        AlternateURL = evtl.AlternateURL,
                        Family = evtl.Family,
                    };
                repository.Add(evt);

                ICategoryRepository categoryRepository = new CategoryRepository();
                foreach (var cat in evtl.Categories)
                {
                    categoryRepository.AddEventCategory(evt.Id, cat.Id);
                }

                return evt.Id.ToString();
            }
            catch(Exception ex)
            {
                return ex.Message;
            }
        }

        [WebMethod]
        public string UpdateEvent(EventLight evtl)
        {
            try
            {
                IEventRepository repository = new EventRepository();
                var evt = repository.GetById(evtl.Id);
                evt.Name = evtl.Name;
                evt.StartDate = Convert.ToDateTime(evtl.StartDate);
                evt.EndDate = Convert.ToDateTime(evtl.EndDate);
                evt.ShortDescription = evtl.ShortDescription;
                evt.LongDescription = evtl.LongDescription;
                evt.Region = evtl.Region;
                evt.Country = evtl.Country;
                evt.State = evtl.State;
                evt.City = evtl.City;
                evt.Location = evtl.Location;
                evt.Family = evtl.Family;
                
                repository.Update(evt);

                ICategoryRepository categoryRepository = new CategoryRepository();
                foreach (var cat in evt.EventCategories)
                {
                    categoryRepository.DeleteEventCategory(evt.Id, cat.Id);
                }

                foreach (var cat in evtl.Categories)
                {
                    categoryRepository.AddEventCategory(evtl.Id, cat.Id);
                }

                return evt.Id.ToString();
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }

        [WebMethod]
        public List<string> GetDistinctRegions()
        {
            IEventRepository repository = new EventRepository();
            var regions = repository.GetDistinctRegions();
            return regions;
        }

        [WebMethod]
        public List<string> GetDistinctCountries(string region)
        {
            IEventRepository repository = new EventRepository();
            var countries = repository.GetDistinctCountries(region);
            return countries;
        }

        [WebMethod]
        public List<string> GetDistinctStates(string country)
        {
            IEventRepository repository = new EventRepository();
            var states = repository.GetDistinctStates(country);
            return states;
        }

        [WebMethod]
        public List<string> GetDistinctCities(string state)
        {
            IEventRepository repository = new EventRepository();
            var cities = repository.GetDistinctCities(state);
            return cities;
        }

        [WebMethod]
        public string CreatePicture(byte[] imageIn, string fileName, string caption, string eventId, bool isListingPhoto, List<Guid> peopleIds, bool isFavorite, int rating, string latitude, string longitude)
        {
            try
            {
                var ms = new MemoryStream(imageIn);
                var b = (Bitmap)Image.FromStream(ms);

                var prefix = ConfigurationManager.AppSettings["UploadPicturePath"];
                // Temporary upload file
                var uploadPath = prefix + "Uploads/" + Path.GetFileName(fileName);
                b.Save(Server.MapPath(uploadPath), System.Drawing.Imaging.ImageFormat.Jpeg);

                IEventRepository eventRepository = new EventRepository();
                Event evt = eventRepository.GetById(new Guid(eventId));

                // Get the Picture Path
                var webPath = Event.BuildImageBasePath(evt) + Path.GetFileName(fileName);
                var finalPath = Server.MapPath(prefix) + webPath;
                var smallfinalPath = Server.MapPath(prefix) + "Small" + webPath;

                // Resize Image and move to final path
                ImageUtility.Resize(Server.MapPath(uploadPath), 583);
                ImageUtility.Move(Server.MapPath(uploadPath), finalPath);

                ImageUtility.Copy(finalPath, smallfinalPath);
                ImageUtility.Resize(smallfinalPath, 292);

                // Get Next PictureCode
                IPictureRepository pictureRepository = new PictureRepository();
                IPeopleRepository peopleRepository = new PeopleRepository();
            
                // Build Picture Object and Add
                var picture = new Picture();
                picture.EventId = new Guid(eventId);
                picture.PictureCode = pictureRepository.GetNextPictureCode();
                picture.Caption = caption;
                picture.ImagePath = webPath;
                picture.IsListing = isListingPhoto;
                picture.IsFavorite = isFavorite;
                picture.Rating = rating;
                picture.Latitude = latitude;
                picture.Longitude = longitude;
                picture.CreatedDate = DateTime.Now;
                picture.ModifiedDate = DateTime.Now;         
                picture.Order = pictureRepository.GetNextOrderByEventID(picture.EventId);
                pictureRepository.Add(picture);

                peopleRepository.DeletePeopleFromPicture(picture.Id);
                foreach (var personId in peopleIds)
                {
                    var p = peopleRepository.GetPeopleById(personId);
                    if(p != null)
                        peopleRepository.AddPeopleToPicture(picture.Id, p.PeopleId);
                }
                pictureRepository.Update(picture);

                return SuccessMessage;
            }
            catch (Exception ex)
            {
                return ex.Message;
            }    
        }

        [WebMethod]
        public string CreateVideo(string eventId, string url, string caption, string duration)
        {
            try
            {
                var videoRepository = new VideoRepository();
                var video = new Video 
                {
                    VideoCode = videoRepository.GetNextVideoCode(),
                    EventId = new Guid(eventId),
                    Caption = caption,
                    Duration = duration,
                    URL = url,
                    IsVisible = true,
                    IsFavorite = false,
                    CreatedDate = DateTime.Now,
                    ModifiedDate = DateTime.Now, 
                    
                };
                videoRepository.Add(video);
                return SuccessMessage;
            }
            catch(Exception ex)
            {
                return ex.Message;

            }
        }

        [WebMethod]
        public List<PeopleLight> GetAllPeople()
        {
            IPeopleRepository peopleRepository = new PeopleRepository();
            return peopleRepository.GetAllPeopleLight();
        }

        [WebMethod]
        public Guid AddPeople(Guid PeopleId, string firstName, string lastName)
        {
            try
            {
                var person = new People();
                if (PeopleId == Guid.Empty)
                {
                    person.PeopleId = Guid.Empty;
                    person.FirstName = firstName;
                    person.MaidenName = string.Empty;
                    person.LastName = lastName;
                    person.IsHuman = true;
                    person.BirthDate = null;
                }
                else
                    person.PeopleId = PeopleId;

                IPeopleRepository repository = new PeopleRepository();
                repository.Add(person);

                return person.PeopleId;
            }
            catch(Exception ex)
            {
                return Guid.Empty;
            }
        }

        [WebMethod]
        public List<CategoryLight> GetCategories()
        {
            ICategoryRepository categoryRepository = new CategoryRepository();
            return categoryRepository.GetAllCategories();
        }

        [WebMethod]
        public bool SaveCategory(string categoryName)
        {
            ICategoryRepository categoryRepository = new CategoryRepository();
            Category category = new Category();
            category.Name = categoryName;
            category.ParentId = new Guid();
            categoryRepository.Add(category);

            return true;
        }

        [WebMethod]
        public bool SaveSubCategory(Guid parentId, string categoryName)
        {
            ICategoryRepository categoryRepository = new CategoryRepository();
            Category category = new Category();
            category.ParentId = parentId;
            category.Name = categoryName;
            categoryRepository.Add(category);

            return true;
        }

        [WebMethod]
        public bool DeletePhoto(Guid photoId)
        {
            IPictureRepository pictureRepository = new PictureRepository();
            Picture picture = pictureRepository.GetById(photoId);
            pictureRepository.Remove(picture);

            return true;
        }
    }
}
